<?php


namespace App\Http\Controllers;


use App\Models\Homepage;
use App\Models\Menu;
use App\Models\News;
use App\Service\ApiResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;

class HomeController
{
    public function index(Request $request)
    {
        $userAgent = $request->userAgent();
        $post = $request->post();
        $type = (isset($post['type']) && $post['type'] == 2) ? true : false;
        $isMobile = (strpos(strtolower($userAgent), 'mobile') !== false || $type == true) ? true : false;
//        $isMobile = strpos(strtolower($userAgent), 'mobile') !== false;
        $isPreview = ($request->post('isPreview')==='true') ? true : false;

        $newsModel = new News();
        $where = [
            'is_delete' => 0,
            'state' => 1,
        ];
        $newsList = $newsModel::select(['id as news_id', 'type', 'title', 'years', 'news_date as date','is_ding as top'])
            ->where($where)
            ->where('issue_time', '<=', date('Y-m-d H:i:s'))
            ->orderBy('is_ding', 'desc')
            ->orderBy('news_date', 'desc')
            ->limit(3)
            ->get();

        $homepageModel = new Homepage();
        $where = $isPreview ?
            [
                'is_delete'=>0,
            ]
        :[
            'is_delete' => 0,
            'state' => 1
        ];

        $cvList = $homepageModel::select(['image1', 'image2', 'linkurl', 'name', 'id'])
            ->where($where);
        if (empty($isPreview)){
            $cvList = $cvList->where('issue_time', '<=', date('Y-m-d H:i:s'));
        }
        $cvList = $cvList
            ->orderBy('orid', 'asc')
            ->orderBy('id', 'desc')
            ->get();
        Log::info('处理前的CV数据是：'.json_encode($cvList));
        foreach ($cvList as $key => $val) {
            $cvList[$key]['image'] = $isMobile ? $val['image2'] : $val['image1'];
            $cvList[$key]['image'] = $homepageModel->getImage1Attribute($val['image']);
            $cvList[$key]['url'] = $val['linkurl'];
        }
        Log::info('处理后的CV数据是：'.json_encode($cvList));

        $menuModel = new Menu();
        $where = [
            'state' => 1,
            'is_delete' => 0,
            'isrecommend' => 1
        ];
        $recommendList = $menuModel::select(['id', 'content_cover as image','cover', 'name'])
            ->where($where)
            ->where('issue_time', '<=', date('Y-m-d H:i:s'))
            ->orderBy('orid', 'asc')
            ->orderBy('id', 'desc')
            ->limit(7)
            ->get();
        foreach ($recommendList as $key => $val) {
            $recommendList[$key]['image'] = $menuModel->getContentCoverAttribute($val['cover']);
            $recommendList[$key]['url'] = env('PREVIEW_URL').'/cookbook/cookdetail/'.$val['id'];
        }

        $where = [
            'state' => 1,
            'is_delete' => 0,
            'ishot' => 1
        ];
        $hotList = $menuModel::select(['id', 'content_cover as image','cover', 'name'])
            ->where($where)
            ->where('issue_time', '<=', date('Y-m-d H:i:s'))
            ->orderBy('orid', 'asc')
            ->orderBy('id', 'desc')
            ->limit(2)
            ->get();
        foreach ($hotList as $key => $val) {
            $hotList[$key]['image'] = $menuModel->getContentCoverAttribute($val['cover']);
            $hotList[$key]['url'] = env('PREVIEW_URL').'/cookbook/cookdetail/'.$val['id'];
        }

        $result = [
            "cv" => [
                "module_type" => 1,
                "module_name" => "首页CV",
                "item" => $cvList
            ],
            "class" => [
                "module_type" => 2,
                "module_name" => "日式咖喱课堂",
                "name" => "日式咖喱课堂",
                "url" => env('PREVIEW_URL')."/index/curry/index"
            ],
            "cookbook" => [
                "module_type" => 3,
                "module_name" => "人气菜谱",
                "item" => $hotList
            ],
            "cookbook2" => [
                "module_type" => 5,
                "module_name" => "花式菜谱",
                "item" => $recommendList,
            ],
            "news" => [
                "module_type" => 4,
                "module_name" => "新闻中心",
                "item" => $newsList
            ]
        ];
        return ApiResponse::success($result);
    }

    public function qianyi()
    {
        $get = $_GET;
        if (isset($get['id'])){
            $id = $get['id'];
        }else{
            $id = null;
        }

        $old = DB::table('old_menu')
            ->where('id','>',38)
            ->get(['id','value_one','value_two','value_three'])
            ->map(function ($item) {
                return (array)$item; // 将每个对象转换为数组
            })
            ->toArray();
        $newData = [];
        foreach ($old as $key => $val)
        {
            $yongliao = json_decode($val['value_one'],true);
            $danwei = json_decode($val['value_two'],true);
            $newYongliao = [];
            foreach ($yongliao as $k => $v)
            {
                $newYongliao[$k] = [
                    '用料'=>$v,
                    '单位'=>$danwei[$k]
                ];
            }
            $zuofa = json_decode($val['value_three'],true);
            $newZuofa = [];
            foreach ($zuofa as $k1 => $v1)
            {
                $newZuofa[$k1] = [
                    '做法'=>$v1
                ];
            }
            $newData[$key] = [
                'id' => $val['id'],
                'method' => json_encode($newZuofa),
                'ingredient' => json_encode($newYongliao)
            ];
        }

        foreach ($newData as $key1 => $val1)
        {
            DB::table('menus')
                ->where('id','=',$val1['id'])
                ->update([
                    'method' => $val1['method'],
                    'ingredient' => $val1['ingredient']
                ]);
        }

        return ApiResponse::success();
    }

    public function testStorage()
    {
        $disk = Storage::disk('remote_storage');
        $testFile = 'cv/images/test.txt';
        $content = 'Test file created at '. now();

        try {
            $disk->put($testFile, $content);
            $exists = $disk->exists($testFile);


            return "测试文件写入成功: {$exists}";
        } catch (\Exception $e) {

            return "测试失败: {$e->getMessage()}";
        }
    }
}
